import { reqCartList ,reqDeleteCartById,reqUpdateCheckCartById} from "@/api"
const state = {
    cartList:[]
}
const mutations = {
    GETCARTLIST(state,cartList){
        state.cartList = cartList
    }
}
const actions = {
    // 获取购物车列表
    async getCartList({commit}){
        let result = await reqCartList()
        // console.log(result);
        if(result.code == 200){
            commit("GETCARTLIST",result.data)
        }
    },
    // 删除购物车某一个产品
    async deleteCartListBySkuId({commit},skuId){
       let result =  await reqDeleteCartById(skuId)
       if(result.code == 200){
        return "ok"
       }else{
        return Promise.reject(new Error("faile"))
       }
    },
    // 修改购物车某一个产品的选中状态
    async updateCheckCartById({commit},{skuId,isChecked}){
        let result = await reqUpdateCheckCartById(skuId,isChecked)
        if(result.code == 200){
            return "ok"
        }else{
            return Promise.reject(new Error("faile"))
        }
    },
    // 删除购物车中选中的所有产品
    deleteAllCheckedCart({dispatch,getters}){
    //context:是当前的小仓库 
    // 获取购物车中全部的信息
        let PromiseAll = []
      getters.cartList.cartInfoList.forEach(item => {
        
        let promise =  item.isChecked == 1 ? dispatch("deleteCartListBySkuId",item.skuId) : ""
        // 将每一次返回的promise添加到数组中
        PromiseAll.push(promise)
      });  
      return Promise.all(PromiseAll)
    },
    // 修改全部产品的状态
    updateAllCartIsChecked({dispatch,state},isChecked){
        let promiseAll = []
        state.cartList[0].cartInfoList.forEach(item=>{
            let promise = dispatch("updateCheckCartById",{skuId:item.skuId,isChecked})
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }
}
const getters ={
    cartList(state){
        return state.cartList[0] || {}
    },
    /* cartInfoList(state){
        return state.cartList[0]
    } */
}

export default ({
    state,
    mutations,
    actions,
    getters
})